package com.edu.java.service.impl;

import com.edu.java.dao.CategoryDao;
import com.edu.java.dao.CategoryPropTemplateDao;
import com.edu.java.dao.PropDao;
import com.edu.java.dao.PropValueDao;
import com.edu.java.entity.Category;
import com.edu.java.entity.CategoryDTO;
import com.edu.java.entity.CategoryProTemplate;
import com.edu.java.entity.Prop;
import com.edu.java.entity.PropDTO;
import com.edu.java.entity.PropValue;
import com.edu.java.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author miaozhiqiang
 * @version 1.0
 * @date 2022/7/16 11:08 下午
 */
@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    PropDao propDao;
    @Autowired
    PropValueDao propValueDao;

    @Autowired
    CategoryPropTemplateDao templateDao;

    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public CategoryDTO getCategoryPropType(CategoryProTemplate template) {
        CategoryDTO categoryDTO = new CategoryDTO();
        if (ObjectUtils.isEmpty(template)) {
            log.info("template is null ");
            return categoryDTO;
        }
        Long categoryId = template.getCategoryId();
        //查询商品类目
        getCategory(categoryId,categoryDTO);
        //根据当前类目获取商品所有属性
        List<Long> propIds;
        propIds = (List<Long>) redisTemplate.opsForList().leftPop("categoryProp" + categoryId);
        if (ObjectUtils.isEmpty(propIds)) {
            propIds = templateDao.findPropId(template.getId());
        }
        List<Prop> propList = propIds.stream().map(x -> {
            Prop prop = getProp(x);
            return prop;
        }).collect(Collectors.toList());
        categoryDTO.setPropList(propList);

        return categoryDTO;
    }

    @Override
    public void addCategoryPropType(PropDTO propDTO) {
        List<Prop> propList = propDTO.getPropList();
        propList.stream().forEach(prop -> {
            propDao.save(prop);
            //添加sku
        });
    }

    private CategoryDTO getCategory(Long categoryId,CategoryDTO categoryDTO) {
        Optional<Category> optional = categoryDao.findById(categoryId);
        if (optional.isPresent()) {
            Category category = optional.get();
            categoryDTO.setCategory(category);
            //进行业务处理
        }
        return categoryDTO;
    }

    private Prop getProp(Long propId) {
        Optional<Prop> optional = propDao.findById(propId);
        Prop prop = new Prop();
        if (optional.isPresent()) {
            prop = optional.get();

        }
        return prop;
    }
}
